﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Xml.Serialization;

namespace MyTimeLine.Util
{
    public static class EnumExtensions
    {
        /// <summary>
        /// Converte a representação string para um Enum
        /// </summary>
        /// <typeparam name="T">Tipo do Enum</typeparam>
        /// <param name="value">valor a ser convertido para Enum.</param>
        /// <returns>Objeto do tipo Enum convertido</returns>
        public static T ParseAsEnum<T>(this string value)
        {
            if (String.IsNullOrEmpty(value))
                throw new ArgumentNullException("value");

            value = value.Trim();

            if (value.Length == 0)
                throw new ArgumentException(string.Format(Mensagens.ValidacaoGenerica_ValorInvalido, "Enum Parse Value"), "value");

            Type enumType = typeof(T);

            if (!enumType.IsEnum)
// ReSharper disable NotResolvedInText
                throw new ArgumentException(string.Format(Mensagens.ValidacaoGenerica_ValorInvalido, "Enum Parse Type"), "T");
// ReSharper restore NotResolvedInText

            return (T)Enum.Parse(typeof(T), value, true);
        }

        /// <summary>
        /// REcuperar A Decrição de um Enum atravez do Atributo  XmlEnum("xxxxxx")
        /// </summary>
        /// <param name="enumeration"></param>
        /// <returns></returns>
        public static string ToDescription(this Enum enumeration)
        {
            var type = enumeration.GetType();
            var memInfo = type.GetMember(enumeration.ToString());

            if (memInfo.Length > 0)
            {
                var attrs = memInfo[0].GetCustomAttributes(typeof(XmlEnumAttribute), false);

                if (attrs.Length > 0)
                    return ((XmlEnumAttribute)attrs[0]).Name;
            }

            return enumeration.ToString();
        }
    }
}
